import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.FilePath.Posix
import System.IO
import System.Cmd

import AbsJavalette
import LexJavalette
import ParJavalette
import ErrM
import PrintJavalette

import AnnotatingTypeChecker
import Compiler


check :: String -> String -> IO ()
check fn s = case pProgram (myLexer s) of
            Bad err -> do hPutStrLn stderr "ERROR"
                          putStrLn "SYNTAX ERROR"
                          putStrLn err
                          exitFailure
            Ok tree -> case checkProgram2 tree of
                          Bad err -> do hPutStrLn stderr "ERROR"
                                        putStrLn err
                                        putStrLn (show tree)
                                        exitFailure
                          Ok at -> do 
                            hPutStrLn stderr "OK"
                            putStrLn (show tree)
                            --putStrLn $ printTree at ++ "OK\n"
                            let cp = (compileProgram at (takeBaseName fn))
                            writeFile ((dropExtension fn)++".j") cp
                            system ("java -jar lib/jasmin.jar " ++ ((dropExtension fn) ++ ".j") ++ " -d " ++ (takeDirectory fn))
                            --system ("java " ++ (takeBaseName fn))
                            return ()

                                         
comp :: Program -> IO ()
comp p = do a <- getArgs
            putStrLn $ takeBaseName $ head a

main :: IO ()
main = do args <- getArgs
          case args of
            [file] -> readFile file >>= (check file)
            _ -> do putStrLn "Usage: lab2 <SourceFile>"
                    exitFailure
